<?php 

/**
 商品控制器 datetime：2016-11-9 19:43 @auth YWH
 */

namespace Admin\Controller;

use Think\Controller;




class GoodsController extends Controller{

	public function index(){
    
    	 $sku_goods          = D('SkuGoods');

          //初始化变量
            $where = '';
            $order = '';
            $limit = '';
            $num   = I('get.num');
            $order = empty($order)?'proudct_id':$order;

        //搜索设置
            if(I('get.keywords')){
                $where = "type_name like '%".I('get.keywords')."%'";
            }else{
                $where = '';
            }

            //设置分页
            //记录总数
            $count = $sku_goods->where($where)->count();

             //创建分页对象
            $page               = new \Think\Mypage($count,$num);

            $sku_goodsArr       = $sku_goods->select();
        
            $proudct            = D('Proudct');

            $typAttr            = D('typAttr');

            $sku                = M('sku_cat');


       
            // NSLog($sku_goodsArr);


            $this->assign($sku_goodsArr);

            $res                = array();

           foreach ($sku_goodsArr as $key => $v) {

            if (!empty($v['sku_id']) || !empty($v['proudct_id']) ) {


            $skuInfo[]       = $sku->where('sku_id='.$v['sku_id'])->select();

            $proudctInfo[]   = $proudct->where('max_id='.$v['proudct_id'])->select();

            $res[]          = array_merge($sku_goodsArr[$key],['skuInfo'=>$skuInfo[$key]],['proudctInfo'=>$proudctInfo[$key]]); 

              
            }
            
            
               // echo  EAN_13('6901028055048');  
                
           }

 // echo date('YmdHi');

           $this->assign('res',$res);
           $this->display();
    }


/**
 加载添加商品模板
 */

    public function add(){
    
    //实例化数据库对象
        $goodsclass = D('Goodstype');
        //查询所有顶级分类
        $one = $goodsclass->where('pid=0')->select();
        //遍历查询所有子类
        foreach($one as $k=>$v){
            $childCid = $goodsclass->where('pid='.$v['id'])->getField('id',true);
            $childName = $goodsclass->where('pid='.$v['id'])->getField('type_name',true);
            //把所有类合并为一个二维数组
            $classes[$v['type_name']] = array_combine($childCid, $childName);


        }



        //分配变量
        $this->assign('classes',$classes);
        $this->display();
    }






    public function detail(){


      

        $this->display();


    }


    public function del(){

        
        $sku_goods          = D('SkuGoods');

        $proudct            = D('Proudct');

        $sku_cat            = D('sku_cat');

        $sku_goods->startTrans();//事务启用
        
        $proudct            = D('Proudct');

        $result1            = $sku_goods->where('sku_id='.$_GET['sku'])->delete();

        $result2            = $sku_cat->where('sku_id='.$_GET['sku'])->delete();

       
        if ($proudct->where('max_id='.$_GET['product'])->count()<=0) {
                
               $result3     = $proudct->where('max_id='.$_GET['product'])->delete();

               
        }



        if($result1 && $result2){

         $sku_goods->commit();//成功则提交

         $this->success('删除成功', '/Admin/Goods/index');

        }else{

         $sku_goods->rollback();//不成功，则回滚

         $this->error('删除失败', '/Admin/Goods/index');

         // echo $result;

        }


       

    }



    public function doDetail(){

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728 ;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg','JPEG');// 设置附件上传类型
        $upload->rootPath = 'Public/Uploads/'; // 设置附件上传根目录
        // 上传单个文件
        $info = $upload->uploadOne($_FILES['files']);
        if(!$info) {// 上传错误提示错误信息
        $this->ajaxReturn($upload->getError());
        exit();
        }else{// 上传成功 获取上传文件信息
           $logo = $info['savepath'].$info['savename'];
           // $this->ajaxReturn('上传成功！');
           // $this->ajaxReturn($logo);
        }

        $proudct_id = $_POST['proudct_id'];

        $detail     = M('detailimg');

        $data = ['detail_img'=>$logo,'proudct_id'=>$proudct_id];


            if ( $detail->add($data)>0) {
                 
                // $detail->getLastSql();exit;

                 $this->ajaxReturn('上传成功！');



            }else{

                $this->ajaxReturn('上传失败');
            }
          
}









   







/**
 ajax 加载属性名option
 */

    public function loadOption(){

        if (IS_AJAX && !empty($_POST['type_id']))
        {
        $typAttr = D('typAttr');

        $type = $typAttr->where('type_id='.I('post.type_id'))->select();

        $this->ajaxReturn($type);

        }else{

           $this->error('删除失败','/Admin/Goods/add');
        }



    }


/**
 ajax 加载属性值option
 */

    public function loadAttrVal(){

        $typAttr = D('AttrVal');

        $attr_val = $typAttr->where('attr_id='.I('post.attr_id'))->select();

        // $attr_val = $typAttr->where('attr_id=19')->select();

        $attr_val[0]['attr_val'] =  json_decode($attr_val[0]['attr_val']);

        // var_dump($attr_val);

        $this->ajaxReturn($attr_val);
    }



    public function insert(){

        if (empty($_POST['paid'])||empty($_POST['prodectsname'])||empty($_POST['price'])||empty($_POST['discount'])||empty($_POST['num'])||empty($_POST['attr_val'])||empty($_POST['attr_val']))
        {
          
            $this->error('请检查字段是否填写完整',U('Admin/Goods/add'),2);


        }


      
/**
 图片上传
 */
        // var_dump($_POST);
        // $upload = new \Think\Upload();// 实例化上传类
        // $upload->maxSize = 3145728 ;// 设置附件上传大小
        // $upload->exts = array('jpg', 'gif', 'png', 'jpeg','JPEG');// 设置附件上传类型
        // $upload->rootPath = 'Public/Uploads/'; // 设置附件上传根目录
        // // 上传单个文件
        // $info = $upload->upload($_FILES['logo']);
        // if(!$info) {// 上传错误提示错误信息
        // $this->error($upload->getError());
        // exit();
        // }else{// 上传成功 获取上传文件信息
        //   $logo[] = $info['savepath'].$info['savename'];
        // }


        $proudct            = D('Proudct');

        $sku                = M('sku_cat');

        $sku_goods          = D('SkuGoods');


        $typAttr1            = D('TypAttr');

        $max_id             = $proudct->max('id');

        $max_id             = $max_id+1;

        $proudct_id         = $max_id;

        $sku_id             = $sku->max('id');
       
        $skuArr  =array();

        $img     = array();


        $proudctArr         = array('cat_id'=>$_POST['paid'],'prodectsname'=>$_POST['prodectsname'],'discount'=>$_POST['discount'],'max_id'=>$max_id);

        $i=0;

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728 ;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = 'Public/Uploads/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        // 上传文件
        $info = $upload->upload();
        if(!$info)
        {// 上传错误提示错误信息
        $this->error($upload->getError());
        }else{// 上传成功 获取上传文件信息
        foreach($info as $key=> $file){
        // echo $file['savepath'].$file['savename'];

            if (empty($file)) {
                break;
            }else{

                $img[$i] =  $file['savepath'].$file['savename'];

                $i++;
            }

           
        }
}


       

        foreach ($_POST['attr_name'] as $key => $value) {
           
                if (($value =='' )||( $_POST['attr_val'][$key] =='')) {

                    break;
                }


        $sku_id             =$sku_id + 1;

        $attr_nameArr       = $typAttr1->where('id='.$_POST['attr_name'][$key])->find();

        $attr_name[$key]          = $attr_nameArr['attr_name'];

        $skuArr[$key]            = ['attr_value'=>$_POST['attr_val'][$key],'attr_name'=>$attr_name[$key],'sku_id'=>$sku_id];


        $sku_goodsArr[$key]       = array('sku_id'=>$sku_id,'price'=>$_POST['price'],'num'=>$_POST['num'],'logo'=>$img[$key],'proudct_id'=>$proudct_id);
        }

// NSLog($skuArr);
// NSLog($_POST);
// NSLog($logo);
// NSLog($_POST['attr_val'][$key]);
// NSLog($skuArr);
// NSLog($sku_goodsArr);
// NSLog($info);
// NSLog($img);
// exit;
        $flag = false;
        $succ = 0;
        $err  = 0;
        $proudct->startTrans();

        if ($proudct->create($proudctArr)) {
           
            $flagP          = $proudct->add();


        foreach ($skuArr as $k => $v) 
        {
            
            $flagS[$k]          = $sku->add($skuArr[$k]);

            $flagG[$k]          = $sku_goods->add($sku_goodsArr[$k]);


             if( ($flagS[$k]>0) && ($flagG[$k]>0))
            {
                $proudct->commit();

                $flag = true;
                $succ++;
               
            }
                else
                {
                    $proudct->rollback();
                  
                    $err++;
                }
    }


           if(flag)
            {
                $proudct->commit();
                
                $this->success('<font color="cyan">'.$succ.'<font/>'.'&nbsp;&nbsp;条数据添加成功<font color="red">'.$err.'<font/>&nbsp;&nbsp条数据添加失败', U('Admin/Goods/add'),3);
            }
                else
                {
                    $proudct->rollback();
                    $this->error('<font color="red">'.$err.'<font/>'.'&nbsp;&nbsp;条数据添加失败,&nbsp;&nbsp数据已经回滚',U('Admin/Goods/add'),3);

                }



        }else{

            $this->error($goods->getError(),U('Admin/Goods/add'),2);
        }

    }





       
  


 // exit();

/**
 实例化模型 三张表 sku_cat Proudct SkuGoods
 */
        

//         $proudct            = D('Proudct');

//         $sku                = M('sku_cat');

//         $sku_goods          = D('SkuGoods');


//         $typAttr1            = D('TypAttr');

//         $max_id             = $proudct->max('id');

//         $max_id             = $max_id+1;

//         $proudct_id         = $max_id;

//         $proudctArr         = array('cat_id'=>$_POST['paid'],'prodectsname'=>$_POST['prodectsname'],'discount'=>$_POST['discount'],'max_id'=>$max_id);

//         $sku_id             = $sku->max('id');


//         $sku_id             =$sku_id + 1;

//         $attr_nameArr       = $typAttr1->where('id='.$_POST['attr_name'])->select();

//         $attr_name          = $attr_nameArr[0]['attr_name'];

     

//         $skuArr             = array('attr_value'=>$_POST['attr_val'],'attr_name'=>$attr_name,'sku_id'=>$sku_id);

       

//         $sku_goodsArr       = array('sku_id'=>$sku_id,'price'=>$_POST['price'],'num'=>$_POST['num'],'logo'=>$logo,'proudct_id'=>$proudct_id);


//         if ($proudct->create($proudctArr) && $sku_goods->create($sku_goodsArr)) {
// /**
//     开启事务，添加数据
//   */ 
//             $proudct->startTrans();

//             $flagP          = $proudct->add();

//             $flagS          = $sku->add($skuArr);

//             $flagG          = $sku_goods->add();

           
// /**
//  判断是否三表插入成功 否则回滚
//  */
//             if(($flagP>0) && ($flagS>0) && ($flagG>0))
//             {
//                 $proudct->commit();

//                 $this->success('添加成功', '/Admin/Goods/add');
//             }
//             else
//             {
//                 $proudct->rollback();
//                 $this->error('添加失败,数据已经回滚','Admin/Goods/add');
//                  // var_dump($flagP);
//             }
//         }else{

//             $this->error($goods->getError().('Admin/Goods/index'),2);
//         }


//         // var_dump($_POST);

// }





}





